package xmachinery

import (
	"fmt"
	"github.com/RichardKnop/machinery/v2/tasks"
	"github.com/google/uuid"
	"github.com/robfig/cron/v3"
)

type ScheduledTask struct {
	Id        string                 //定时任务id
	TaskCode  string                 //machinery任务编码
	Spec      string                 //cron表达式
	TaskQueue string                 //任务队列(空为默认)
	Headers   map[string]interface{} //任务签名头
	Args      []tasks.Arg            //任务参数
	entryId   cron.EntryID           //定时任务实例ID
}

func NewScheduledTask(id, taskCode, spec, taskQueue string, args ...tasks.Arg) *ScheduledTask {
	return &ScheduledTask{
		Id:        id,
		TaskCode:  taskCode,
		Spec:      spec,
		TaskQueue: taskQueue,
		Args:      args,
	}
}

func (task *ScheduledTask) Equal(other *ScheduledTask) bool {
	if !(task.Id == other.Id && task.TaskCode == other.TaskCode && task.Spec == other.Spec && task.TaskQueue == other.TaskQueue) {
		return false
	}
	if len(task.Args) != len(other.Args) {
		return false
	}
	if len(task.Args) == 0 {
		return true
	}
	for i, arg := range task.Args {
		if arg != other.Args[i] {
			return false
		}
	}
	if len(task.Headers) != len(other.Headers) {
		return false
	}
	if len(task.Headers) == 0 {
		return true
	}
	for k, v := range task.Headers {
		ov, ok := other.Headers[k]
		if !ok || v != ov {
			return false
		}
	}
	return true
}

func (task *ScheduledTask) Signature() *tasks.Signature {
	signatureID := uuid.New().String()
	return &tasks.Signature{
		UUID:       fmt.Sprintf("scheduledTask_%s_%s", task.Id, signatureID),
		Name:       task.TaskCode,
		Headers:    task.Headers,
		Args:       task.Args,
		RoutingKey: task.TaskQueue,
	}
}
